package client

import (
	"fmt"
	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"goods-srv/libs"
)

// 使用了github.com/mbobakov/grpc-consul-resolver 这个包，实现多个微服务之间负载均衡，内部实现解析，很重要

// GrpcConsulClientConn grpc 连接 consul 动态获取服务连接
func GrpcConsulClientConn(serverName string) (*grpc.ClientConn, error) {
	conn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s", // &tag=primary，tag 可以忽略
			libs.ConsulConfig.Address,
			libs.ConsulConfig.Port,
			serverName,
		), // serverName是注册服务时设置的
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), // 策略
	)
	//defer conn.Close()
	return conn, err
}
